import { defineStore } from 'pinia';
import {getCurrentUserMenu} from '../api/menu';
import {AppStoreState, UserInfo} from './types';

export const sysStore = defineStore('sysInfo', {
    state: (): AppStoreState => {
        return {
            isLoadRoute: false, //是否加载路由
            menuList: [], //菜单列表
            permissions: [], //权限列表
            breadcrumbs: [], //面包屑
            routerList: [], //路由列表
            userInfo: {
                id: 0,
                username: '',
                name: '',
                avatar: '',
                phone: ''
            }
        }
    },
    // getters 用于计算基于 state 的值
    getters: {
        getUser: (state) => state.userInfo,
    },
    // actions 用于定义可以修改 state 的函数
    actions: {
        // async getInfo() {
        //     const { data } = await getInfo({})
        //     this.menuList = data.routers;
        //     this.permission = data.permission;
        //     this.isLoadRoute = true;
        //     this.userInfo = data.user || {};
        // },
        setRouterList(data: MenuForm[]) {
            data.forEach((item: MenuForm) => {
                //定义一个对象-->routerInfo格式化后端传入的路由信息
                let routerInfo = {
                    path: item.path,//组件访问路径
                    name: item.title,
                    meta: {name: item.title},
                    component: () => import(`../views${item.path}.vue`),//组件的位置
                }
                this.routerList.push(routerInfo)
            })
        },

        // 缓存用户信息
        setUser(user: UserInfo) {
            this.userInfo = user;
        },
        // 清除用户信息
        clearUser() {
            this.userInfo = {avatar: '', id: 0, phone: '', username: '', name: ''};
        },

    },
    persist: true
});

import {computed, reactive, ref} from 'vue'
import {MenuForm} from "../api/menu/types/menu.dto.ts";

export const useMenuInfoStore = defineStore('menuInfo', () => {
    //获取标识符
    const menuFlag= ref<Boolean>(false)
    //获取菜单是否获取标识符
    const getMenuFlag= computed(()=>menuFlag.value)
    //响应式菜单集合数据
    const menuListInfo= reactive<Array<MenuForm>>([]);

    //获取菜单权限
    const getMenu= computed(async ()=>{
        //判断是否有权限
        if(!menuFlag.value){
            await getMenuByUser();
        }
        menuFlag.value=true;
        return menuListInfo;
    })
    //发送请求获取用户可访问菜单权限
    async function getMenuByUser(){
        try{
            const result = await getCurrentUserMenu()
            menuListInfo.push(...result.data)
        }catch(e){
            console.log(e)
        }
    }
    return {getMenu,getMenuFlag}
})